package com.example.venue_reservation_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.venue_reservation_service.converter.ListConverter;
import com.example.venue_reservation_service.domain.SensitiveWord;
import com.example.venue_reservation_service.dto.SensitiveWordDTO;
import com.example.venue_reservation_service.dto.WordDTO;
import com.example.venue_reservation_service.exception.SensitiveWordException;
import com.example.venue_reservation_service.mapper.SensitiveWordMapper;
import com.example.venue_reservation_service.service.SensitiveWordService;
import com.example.venue_reservation_service.utils.RedisUtil;
import com.example.venue_reservation_service.vo.QueryVO;
import com.example.venue_reservation_service.vo.Result;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Optional;

/**
 * 敏感词业务实现类
 */
@Service
public class SensitiveWordServiceImpl extends ServiceImpl<SensitiveWordMapper, SensitiveWord> implements SensitiveWordService {

    @Resource
    private SensitiveWordMapper sensitiveWordMapper;

    @Resource
    private RedisUtil redisUtil;

    private final static String REDIS_KEY = "sensitive-word";

    /**
     * 分页查询敏感词列表
     */
    @Override
    public Result getSensitiveWords(WordDTO dto) {
        Page<SensitiveWord> page = new Page<>(dto.getCurrent(), dto.getSize());
        LambdaQueryWrapper<SensitiveWord> wrapper = new LambdaQueryWrapper<>();
        Integer level = dto.getLevel();
        if(level != 0){
            wrapper.eq(SensitiveWord::getLevel, level);
        }
        wrapper.orderByDesc(SensitiveWord::getUpdateTime);
        page = page(page, wrapper);
        QueryVO<SensitiveWord> vo = new QueryVO<>();
        vo.setList(page.getRecords());
        vo.setTotal(page.getTotal());
        return Result.ok(vo).message("查询成功");
    }

    /**
     * 添加敏感词
     */
    @Override
    public Result addSensitiveWord(SensitiveWordDTO dto) {
        // 去空格后判断是否重复
        String word = dto.getWord().trim();
        if (count(new LambdaQueryWrapper<SensitiveWord>().eq(SensitiveWord::getWord, word)) > 0) {
            return Result.fail().message("该敏感词已存在");
        }
        SensitiveWord sensitiveWord = BeanUtil.copyProperties(dto, SensitiveWord.class);
        sensitiveWord.setWord(word);
        sensitiveWord.setStatus(0); // 默认不启用
        sensitiveWord.setCreateTime(LocalDateTime.now());
        sensitiveWord.setUpdateTime(LocalDateTime.now());
        save(sensitiveWord);
        return Result.ok().message("添加成功");
    }

    /**
     * 修改敏感词信息
     */
    @Override
    public Result updateSensitiveWord(SensitiveWord word) {
        if(Optional.ofNullable(word).isEmpty() || Optional.ofNullable(word.getId()).isEmpty()){
            return Result.fail().message("敏感词记录不存在");
        }
        SensitiveWord origin = getById(word.getId());
        if(!origin.getWord().equals(word.getWord())){
            // 修改了敏感词内容
            if (count(new LambdaQueryWrapper<SensitiveWord>().eq(SensitiveWord::getWord, word.getWord())) > 0) {
                return Result.fail().message("该敏感词已存在");
            }
        }
        updateById(word);
        return Result.ok().message("修改成功");
    }

    /**
     * 删除敏感词
     */
    @Override
    public Result removeSensitiveWord(Integer id) {
        SensitiveWord word = getById(id);
        if(Optional.ofNullable(word).isEmpty()){
            return Result.fail().message("未查询到相关敏感词信息");
        }
        if (word.getStatus() == 1) {
            return Result.fail().message("该敏感词已启用，请先进行禁用");
        }
        removeById(id);
        return Result.ok().message("删除成功");
    }

    @Override
    public Result set(Integer id) {
        SensitiveWord word = getById(id);
        if(Optional.ofNullable(word).isEmpty()){
            return Result.fail().message("未查询到相关敏感词信息");
        }
        Integer status = word.getStatus();
        word.setStatus(status == 1 ? 0 : 1);
        updateById(word);
        try {
            redisUtil.set(REDIS_KEY, ListConverter.listToString(sensitiveWordMapper.selectWordsOrderedByPriority()));
        } catch (Exception e) {
            log.error("更新敏感词库缓存失败，ID:{}"+ e.getMessage());
            throw new SensitiveWordException("SENSITIVE_002", "敏感词状态更新失败，请稍后重试", e);
        }
        return Result.ok().message("设置成功");
    }

}
